var videosOffline = new Array();
var count = 0;
var nbChaines = 0;
var nbHub = 0;
var nbAll = 0;
var dmState = 0;

function ready() {
	count = count + 1;
	// $('#loader').html(count);
	if (count >= videos.length) {
		$('#loader').removeClass('loading');
		displayNbChaines();
	}
}

function init() {
	$('#loader').addClass('loading');
	loadPlaylist();
}

function loadPlaylist() {

}

var timer;
function toggleAutoRefresh() {
	if (timer == null) {
		var time = 60000;
		refreshDesc();
		timer = setInterval("refreshDesc()", time);
	} else {
		clearInterval(timer);
		timer = null;
	}
}

function displayNbChaines() {
	elt = $('#nbChaines');
	if (nbChaines > 0) {
		elt.show();
		elt.html(nbChaines);
	} else {
		elt.hide();
	}

	elt2 = $('#nbHub');
	if (nbHub > 0) {
		elt2.show();
		elt2.html(nbHub);
	} else {
		elt2.hide();
	}

	elt3 = $('#nbAll');
	nbAll = nbChaines + nbHub;
	if (nbAll > 0) {
		elt3.show();
		elt3.html(nbAll);
	} else {
		elt3.hide();
	}

}

function setDesc(id) {
	setDesc(id, null, null, 0);
}

function setDesc(id, onair, title, count) {
	desc = $('#' + id + " p");

	if (title != null) {
		descrition = title;
	} else {
		descrition = desc.text();
	}
	if (count != 0) {
		descrition = descrition + ' (' + count + ')';
	}
	$(desc).text('');
	if (onair == null) {

	} else if (onair) {
		status = $('<span/>', {
			class : 'label label-success icon-live',
			html : 'Live'
		});

		$(desc).css("font-weight", "bold");

		// if (videos[i].type == 'o3D' || videos[i].type == 'jtv') {
		// nbHub = nbHub + 1;
		// } else {
		nbChaines = nbChaines + 1;
		// }

	} else {
		status = $('<span/>', {
			class : 'label icon-live',
			html : 'Off'
		});
		$(desc).css("font-weight", "none");
	}

	$('<span/>', {
		class : 'fill',
		html : descrition
	}).appendTo(desc);

	if (status) {
		status.appendTo(desc);
	}
}

var currentPlayer;
var videotoload;

function initLSPlayer(videoId) {

	params = {
		allowScriptAccess : 'always',
		allowFullScreen : "true",
		wmode : "opaque"
	};
	flashvars = {
		channel : videoId,
		autoPlay : "true",

	// http://cdn.livestream.com/grid/LSLibrary.swf
	};
	var atts = {
		id : "live"
	};
	swfobject.embedSWF("http://cdn.livestream.com/grid/LSPlayer.swf", "live",
			"100%", "100%", "9.0.0", "expressInstall.swf", flashvars, params,
			atts);
	lsplayer = document.getElementById("live");
	currentPlayer = lsplayer;
}
// function livestreamPlayerCallback(event) {
// if (event == 'ready') {
// lsplayer = document.getElementById("live");
// currentPlayer = lsplayer;
// // if (lsplayer.isLive()) {
// // lsplayer.startPlayback(0);
// // }
// // lsplayer.showFullscreenButton(true);
// // lsplayer.showPlayButton(true);
// // lsplayer.showPauseButton(true);
// // lsplayer.showMuteButton(true);
// // lsplayer.showThumbnail(true);
// // $('#tvtitle').html(
// // lsplayer.getChannelDescription() + ' ('
// // + lsplayer.getViewerCount() + ')');
// }
// }

function initDMPlayer(videoId) {
	var params = {
		allowScriptAccess : "always",
		allowFullScreen : "true"
	};
	var atts = {
		id : "live"
	};
	// var flashvars = {
	// // autoplay:"1"
	// // ,enableApi: "1"
	// // ,playerapiid:"dmplayer"
	// // ,hideInfos:"0"
	// };
	swfobject.embedSWF("http://www.dailymotion.com/swf/" + videoId
			+ "&autoplay=1&enableApi=1&playerapiid=dmplayer&hideInfos=1",
			"live", "100%", "100%", "9", null, null, params, atts);
}
function onDailymotionPlayerReady(playerId) {
	if (playerId == 'dmplayer') {

		dmplayer = document.getElementById("live");
		dmplayer.unMute();

		dmplayer.addEventListener("onStateChange", "ondmplayerStateChange");
		status = document.getElementById("status");

		dmplayer.playVideo();
		currentPlayer = dmplayer;
	}
}

function initJTVPlayer(videoId) {
	var params = {
		allowScriptAccess : "always",
		allowFullScreen : "true",
		allowNetworking : "all"
	};
	var atts = {
		id : "live"
	};
	var flashvars = {
		auto_play : "true",
		hostname : "fr.twitch.tv",
		channel : videoId,
		custom : "true",
		start_volume : "25"
	};

	swfobject.embedSWF(
			"http://fr.twitch.tv/widgets/live_embed_player.swf?channel="
					+ videoId, "live", "100%", "100%", "9", null, flashvars,
			params, atts);

	jtvplayer = document.getElementById("live");
	currentPlayer = jtvplayer;
}

function initO3DPlayer(videoId) {
	var params = {
		allowScriptAccess : "always",
		allowFullScreen : "true",
		allowNetworking : "all"
	};
	var atts = {
		id : "live"
	};
	var flashvars = {
		autoplay : "true"
	};

	swfobject.embedSWF("http://www.own3d.tv/livestream/" + videoId
			+ ";autoplay=true", "live", "100%", "100%", "9", null, flashvars,
			params, atts);

	o3dplayer = document.getElementById("live");
	currentPlayer = o3dplayer;
}

function loadVideos(id, url, title, lim, page) {
	videosElt = document.getElementById('videos');

	$.ajax({
		url : url,
		async : false,
		data : {
			limit : lim,
			page : page
		},
		cache : false,
		dataType : 'json',
		success : function(ret) {

			var vids = ret.list;

			if (page < 2) {
				var div5 = document.createElement('div');
				div5.setAttribute('class', 'span4');
				videosElt.appendChild(div5);

				h3 = document.createElement('h2');
				$(h3).html(title);
				div5.appendChild(h3);

				ul = document.createElement('ul');
				ul.setAttribute('id', id);
				div5.appendChild(ul);
			} else {
				ul = document.getElementById(id);
			}
			for ( var i = 0; i < vids.length; i++) {
				var newli = document.createElement('li');
				ul.appendChild(newli);

				vid = vids[i];
				vid.mode = 'vod';
				vid.type = 'dm';
				videosOffline.push(vid);

				var newa = document.createElement('a');
				newa.setAttribute('href', 'javascript:void(0);');
				newa.setAttribute('onclick', 'playOff('
						+ (videosOffline.length - 1) + ')');

				$(newa).html(vid.title);

				newli.appendChild(newa);

				newli.appendChild(document.createElement('br'));

			}
			if (ret.has_more && page < 2) {
				// <ul class="pager">
				// <li><a href="#">Previous</a></li>
				// <li><a href="#">Next</a></li>
				// </ul>
				// </div>
				ulpager = document.createElement('ul');
				ulpager.setAttribute('class', 'pager');
				ulpager.setAttribute('id', 'ulpager' + id);
				div5.appendChild(ulpager);

				var newli = document.createElement('li');
				ulpager.appendChild(newli);
				var newa = document.createElement('a');
				newa.setAttribute('id', 'ulpagera' + id);
				newa.setAttribute('href', 'javascript:void(0);');
				newa
						.setAttribute('onclick', 'loadVideos("' + id + '","'
								+ url + '", "' + title + '", ' + lim + ','
								+ (page + 1) + ')');
				$(newa).html("Plus ...");
				newli.appendChild(newa);

			} else if (ret.has_more) {
				$('#ulpagera' + id).attr(
						"onclick",
						'loadVideos("' + id + '","' + url + '", "' + title
								+ '", ' + lim + ',' + (page + 1) + ')');
			} else {
				$('#ulpager' + id).remove();
			}
		}
	});
}

function ondmplayerStateChange(newState) {
	status.innerHTML = "Main player's new state: " + newState;
}

function refreshDesc() {
	count = 0;
	nbChaines = 0;
	nbHub = 0;
	// $('#loader').addClass('loading');
	$('.streams').each(function(index) {
		request($(this).attr('id'));
	});
}

function request(id) {
	if ($('#' + id).hasClass('dm')) {
		requestDM(id);
	} else if ($('#' + id).hasClass('jtv')) {
		requestJTV(id);
	} else if ($('#' + id).hasClass('ls')) {
		requestLS(id);
		// } else if (videos[i].type == 'o3d') {
		// requestO3D(i);
	} else {
		// setDesc(id);
	}

}

function requestDM(id) {
	var onairurl = 'https://api.dailymotion.com/video/' + id
			+ '?fields=onair,title,mode,views_last_hour';
	$.ajax({
		url : onairurl,
		cache : false,
		dataType : 'json',
		success : function(ret) {
			setDesc(id, ret.onair, ret.title, 0);
		},
		error : function(ret) {
			setDesc(id);
		}
	});
}

function requestLS(id) {
	var onairurl3 = 'http://x' + id
			+ 'x.api.channel.livestream.com/2.0/livestatus.json';
	$.ajax({
		url : onairurl3,
		cache : false,
		dataType : 'jsonp',
		success : function(ret) {
			setDesc(id, ret.channel.isLive, null,
					ret.channel.currentViewerCount);
		},
		error : function(ret) {
			// setDesc(id);
		}
	});
}

function requestJTV(id) {
	var onairurl2 = 'http://api.justin.tv/api/stream/list.json?jsonp=?';
	$.ajax({
		url : onairurl2,
		cache : false,
		dataType : 'json',
		data : {
			channel : id
		},
		success : function(ret) {
			alert(ret);
			oa = ret[0] != '';
			setDesc(id, oa, ret[0].title, ret[0].channel_count);
		},
		error : function(ret) {
			// setDesc(id);
		}
	});
}

function requestO3D(id) {
	// $.ajax({
	// url : "xml2json.php",
	// cache : false,
	// data : {
	// feed : "http://api.own3d.tv/liveCheck.php?live_id="
	// + videos[i].id
	// },
	// // dataType : 'jsonp',
	// success : function(ret) {
	// videos[i].onair = ret.liveEvent.isLive == "true";
	// videos[i].count = ret.liveEvent.liveViewers;
	// videos[i].title = videos[i].name;
	// videos[i].mode = 'live';
	// ready();
	// setDesc(i);
	// },
	// error : function(xhr, ajaxOptions, thrownError) {
	// // alert(xhr.statusText);
	// // alert(xhr.responseText);
	// // alert(xhr.status);
	// // alert(thrownError);
	// ready();
	// setDesc(i);
	// }
	//
	// });
	//
}

function play(i) {
	// if (videos[i].type == 'jtv') {
	// openVideo(videos[i]);
	// } else {
	playVideo(videos[i]);
	// }
}

function jumpToAnchor(cible) {
	$('html, body').animate({
		scrollTop : $(cible).offset().top
	});
}

function play(id) {
	load(id);
	$('#tvtitle').html($('#' + id).title);
	jumpToAnchor("#top");
}

function load(id) {
	if ($('#' + id).hasClass('dm')) {
		loadOnDM(id);
	} else if ($('#' + id).hasClass('ls')) {
		loadOnLS(id);
	} else if ($('#' + id).hasClass('jtv')) {
		loadOnJTV(id);
	} else if ($('#' + id).hasClass('o3d')) {
		loadOnO3D(id);
	}

}
function loadOnO3D(videoId) {
	initO3DPlayer(videoId);
}
function loadOnJTV(videoId) {
	// if (currentPlayer && currentPlayer == jtvplayer) {
	// jtvplayer.play_live(videoId);
	// } else {
	initJTVPlayer(videoId);
	// }
}
function loadOnDM(videoId) {
	if (currentPlayer && currentPlayer == dmplayer) {
		dmplayer.loadVideoById(videoId);
	} else {
		initDMPlayer(videoId);
	}
}
function loadOnLS(videoId) {
	// if (currentPlayer && currentPlayer == lsplayer) {
	// lsplayer.load(videoId);
	// if (lsplayer.isLive()) {
	// lsplayer.startPlayback(0);
	// }
	// } else {
	// videotoload = videoId;
	initLSPlayer(videoId);
	// }
}

function stop() {
	// dmplayer.stopVideo();
	// lsplayer.stopPlayback();
	currentPlayer = null;
	$("#live").remove();
	$("#tvtitle").html("Web TV");
	$('<div id="live">').appendTo('.liveContainer');
}
function showModal() {
	$('#connectModal').modal('show');
}
